package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GroupAnagrams {

    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) {
            return List.of();
        }
        Map<String, List<String>> map = new HashMap<>();
        for (String s : strs) {
            String strEach = toSorted(s);
            List<String> strings = map.get(strEach);
            if (null != strings) {
                strings.add(s);
            } else {
                List<String> list = new ArrayList<>();
                list.add(s);
                map.put(strEach, list);
            }
        }
        return map.values().stream().toList();
    }

    public List<List<String>> groupAnagrams1(String[] strs) {
        if (strs.length == 0) {
            return List.of();
        }
        List<List<String>> result = new ArrayList<>();
        List<String> first = new ArrayList<>();
        first.add(strs[0]);
        result.add(first);
        for (int i = 1; i < strs.length; i++) {
            boolean found = false;
            String s = strs[i];
            String strEach = toSortedString(s);
            for (List<String> out : result) {
                String one = out.getFirst();
                String strExist = toSortedString(one);
                if (strEach.equals(strExist)) {
                    out.add(s);
                    found = true;
                    break;
                }
            }
            if (!found) {
                List<String> newStr = new ArrayList<>();
                newStr.add(s);
                result.add(newStr);
            }
        }
        return result;
    }

    private static String toSortedString(String s) {
        char[] charArray = s.toCharArray();
        List<Character> list = new ArrayList<>();
        for (char c : charArray) {
            list.add(c);
        }
        List<Character> sorted = list.stream().sorted().toList();
        return sorted.toString();
    }


    private static String toSorted(String str) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return String.valueOf(chars);
    }

    private static Set<Character> toSet(String s) {
        char[] charArray = s.toCharArray();
        Set<Character> set = new HashSet<>();
        for (char c : charArray) {
            set.add(c);
        }
        return set;
    }

    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        GroupAnagrams groupAnagrams = new GroupAnagrams();
        List<List<String>> lists = groupAnagrams.groupAnagrams(strs);
        System.out.println(lists);
    }
}
